/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';
import { usePointContext } from './PointContext';
import { ChildLineCommandProps } from './types';

type FormDataType = {
  startPoint: pickedVertexData;
  endPoint: pickedVertexData;
  percent: number;
  surface: pickedFaceData;
};

export function PointBetween({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) {
  const [formData, setFormData] = useState<FormDataType>({
    startPoint: undefined,
    endPoint: undefined,
    percent: 0.5,
    surface: undefined,
  });

  const { picker } = useTools();
  const { setSharedPoint } = usePointContext();

  useEffect(() => {
    excuteData();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const point1 = props?.params?.point1;
      const point2 = props?.params?.point2;
      const surface = props?.params?.surface;

      if (surface) {
        await initEditDependency([
          point1,
          point2,
          props?.params?.plane,
          props?.params?.surface,
        ]);
      } else {
        await initEditDependency([point1, point2, props?.params?.plane]);
      }

      const defaultStartPoint = point1
        ? (picker.generatePickObjByPickID(point1) as pickedVertexData)
        : undefined;
      const defaultEndPoint = point2
        ? (picker.generatePickObjByPickID(point2) as pickedVertexData)
        : undefined;
      const defaultPercent = props?.params?.percent
        ? props?.params?.percent
        : 0;
      const defaultPlane = surface
        ? (picker.generatePickObjByPickID(surface) as pickedFaceData)
        : undefined;
      setFormData({
        startPoint: defaultStartPoint,
        endPoint: defaultEndPoint,
        percent: defaultPercent,
        surface: defaultPlane,
      });
    }
  }, [editDxid]);

  const isFormDataValid = () => {
    const { startPoint, endPoint, percent } = formData;
    return startPoint != null && endPoint != null && percent != null;
  };

  const checkAndFinishDraw = async () => {
    const { startPoint, endPoint, percent } = formData;
    if (isEmpty(startPoint) || isEmpty(endPoint)) {
      return;
    }
    if (percent === null) {
      return;
    }

    const startVertext = startPoint?.vertexId;
    const endVertext = endPoint?.vertexId;

    if (startVertext === endVertext) {
      MessageTip.error('起点和终点不可重合');
      return;
    }

    await excuteData(false);
    onClose();
  };

  const {
    previewCmdResult,
    initEditDependency,
    initingEdit,
    isLoading,
    clear,
    confirmCommand,
  } = useCommand('cmd-between-point', {
    onClose,
    finishDraw: checkAndFinishDraw,
    commandName: 'CreateVertex',
    editDxid: editDxid || props?.shape,
  });

  /**
   * 这里在
   * - 预览结果更新时，更新共享点数据
   * - 在编辑模式时，也会更新共享点数据
   */
  useEffect(() => {
    const pointdata = previewCmdResult?.data?.[0]?.points?.[0];
    if (pointdata) {
      setSharedPoint(pointdata);
    } else {
      setSharedPoint(null);
    }
  }, [previewCmdResult]);

  const excuteData = async (preview: boolean = true) => {
    const { startPoint, endPoint, percent, surface } = formData;
    if (isEmpty(startPoint) || isEmpty(endPoint) || percent === null) {
      clear();
      return;
    }

    let allParma = {};

    if (isEmpty(surface)) {
      allParma = {
        a: {
          mode: '2point',
          point1: startPoint.vertexId,
          point2: endPoint.vertexId,
          percent: percent,
        },
      };
    } else {
      const planeId = surface?.meshId;
      allParma = {
        a: {
          mode: '2point',
          point1: startPoint.vertexId,
          point2: endPoint.vertexId,
          percent: percent,
          surface: planeId,
        },
      };
    }

    await confirmCommand(allParma, preview);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      startPoint: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      endPoint: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      percent: {
        type: 'number',
        title: '比率',
        multipleOf: 0.1,
      },
      surface: {
        type: 'string',
        format: PickInputRJSFFormat.PickPlane,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        const data = {
          startPoint: !isEmpty(v.startPoint) ? v.startPoint : undefined,
          endPoint: !isEmpty(v.endPoint) ? v.endPoint : undefined,
          percent: v.percent,
          surface: v.surface,
        };
        setFormData(data);
      }}
      extraUiSchema={{
        startPoint: {
          'ui:placeholder': '请输入起点',
          'ui:autofocus': true,
        },
        endPoint: {
          'ui:placeholder': '请输入终点',
        },
        percent: {
          'ui:placeholder': '请输入比率',
        },
        surface: {
          'ui:placeholder': '支持面(选填)',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}
